#! /usr/bin/python

import os
import pdfrw


INVOICE_TEMPLATE_PATH = 'a.pdf'
INVOICE_OUTPUT_PATH = 'invoice.pdf'



def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict, which="pacg"):
    if which == "pacg":
        pacg_write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict)

def pacg_write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    ANNOT_KEY = '/Annots'
    ANNOT_FIELD_KEY = '/T'
    ANNOT_VAL_KEY = '/V'
    ANNOT_RECT_KEY = '/Rect'
    SUBTYPE_KEY = '/Subtype'
    WIDGET_SUBTYPE_KEY = '/Widget'
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) 
    #annotations = template_pdf.pages[0][ANNOT_KEY]
    # only one page
    annotations =  template_pdf.Root.Pages.Kids[0].Annots
    for annotation in annotations:
        if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
            if annotation[ANNOT_FIELD_KEY]:
                key = annotation[ANNOT_FIELD_KEY][1:-1]
                #print(key)
                if key in data_dict.keys():
                    annotation.update(
                        pdfrw.PdfDict(AP='{}'.format(data_dict[key]), V='{}'.format(data_dict[key]))
                    )
    pdfrw.PdfWriter().write("tmp/" + output_pdf_path, template_pdf)


data_dict = {
   'Text_1': 'chagncai xie',  #fist name + last name
   'Text_2': '12/23 10:00',  #sample date
}

if __name__ == '__main__':
    write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)
